import { loadMicroApp, MicroApp } from "qiankun";
import microAppJson from "./mirco.json";

let currentApp: MicroApp | null = null;
let currentKey: string | null = null;

// 手动加载子应用
export const LoadMicroApp = (key: string) => {
  if (currentKey === key) {
    // 同一个子应用，不重复加载
    return;
  }

  // 不同子应用，先卸载旧的
  if (currentApp) {
    currentApp.unmount();
    currentApp = null;
  }

  const configMap: Record<string, any> = { ...microAppJson };
  const config = configMap[key];

  if (config) {
    currentApp = loadMicroApp(config, {
      sandbox: {
        // 样式隔离
        experimentalStyleIsolation: true,
      },
    });
    currentKey = key;
  } else {
    console.log(`No micro app found for ${key}`);
  }
};

// 匹配当前路径对应的子应用
export const findRouteMatch = (routes: any[], pathname: string): any => {
  for (const route of routes) {
    if (pathname.startsWith(route.path)) {
      if (route.children) {
        const childMatch = findRouteMatch(route.children, pathname);
        if (childMatch) return childMatch;
      }
      return route;
    }
  }
  return null;
};
